package com.bjgzy.courselive.mvp.ui.activity;

import android.app.Activity;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.bjgzy.courselive.di.component.DaggerCoursePlayComponent;
import com.bjgzy.courselive.di.module.CoursePlayModule;
import com.bjgzy.courselive.mvp.contract.CoursePlayContract;
import com.bjgzy.courselive.mvp.model.entity.CoursePlayData;
import com.bjgzy.courselive.mvp.presenter.CoursePlayPresenter;
import com.bjgzy.module_couselive.R;
import com.bjgzy.module_couselive.R2;
import com.blankj.utilcode.util.ObjectUtils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.eduhzy.ttw.commonres.utils.RxUtil;
import com.eduhzy.ttw.commonres.view.LandLayoutVideo;
import com.eduhzy.ttw.commonsdk.core.Constants;
import com.eduhzy.ttw.commonsdk.core.EventBusTags;
import com.eduhzy.ttw.commonsdk.core.RouterHub;
import com.eduhzy.ttw.commonsdk.entity.CourseCommentData;
import com.eduhzy.ttw.commonsdk.entity.CourseListData;
import com.eduhzy.ttw.commonsdk.holder.AutoBaseViewHolder;
import com.eduhzy.ttw.commonsdk.utils.Utils;
import com.jess.arms.base.BaseActivity;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.qmuiteam.qmui.widget.QMUIEmptyView;
import com.qmuiteam.qmui.widget.dialog.QMUITipDialog;
import com.qmuiteam.qmui.widget.roundwidget.QMUIRoundButton;
import com.shuyu.gsyvideoplayer.GSYVideoManager;
import com.shuyu.gsyvideoplayer.builder.GSYVideoOptionBuilder;
import com.shuyu.gsyvideoplayer.listener.GSYSampleCallBack;
import com.shuyu.gsyvideoplayer.utils.Debuger;
import com.shuyu.gsyvideoplayer.utils.OrientationUtils;
import com.shuyu.gsyvideoplayer.video.base.GSYVideoPlayer;
import com.shuyu.gsyvideoplayer.video.base.GSYVideoView;
import com.umeng.analytics.MobclickAgent;

import org.simple.eventbus.Subscriber;

import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.jess.arms.utils.Preconditions.checkNotNull;

/**
 * @author xubo
 * @date 2018-8-2 9:06:52
 */
@Route(path = RouterHub.COURSELIVE_COURSEPLAYACTIVITY)
public class CoursePlayActivity extends BaseActivity<CoursePlayPresenter> implements CoursePlayContract.View {
    @BindView(R2.id.emptyView)
    QMUIEmptyView emptyView;
    @BindView(R2.id.btn_submit)
    QMUIRoundButton btnSubmit;
    OrientationUtils orientationUtils;

    @Autowired(name = Constants.ROUTER_DATA)
    CourseListData mData;

    private boolean isPlay;
    private boolean isPause;
    private GSYVideoOptionBuilder gsyVideoOption;
    private CoursePlayData mCoursePlayData;
    @BindView(R2.id.rv_list)
    RecyclerView rvList;
    @BindView(R2.id.swipeLayout)
    SwipeRefreshLayout swipeLayout;

    @Inject
    RecyclerView.LayoutManager layoutManager;
    @Inject
    List<CourseCommentData> lists;
    @Inject
    BaseQuickAdapter<CourseCommentData, AutoBaseViewHolder> mAdapter;
    private ViewHolder vh;

    @Override
    protected void onResume() {
        getCurPlay().onVideoResume(false);
        super.onResume();
        isPause = false;
    }

    @Override
    protected void onPause() {
        getCurPlay().onVideoPause();
        super.onPause();
        isPause = true;
    }

    @Override
    protected void onDestroy() {
        if (isPlay && getCurPlay() != null) {
            getCurPlay().release();
        }
        if (orientationUtils != null)
            orientationUtils.releaseListener();
        super.onDestroy();
    }

    @Override
    public void setupActivityComponent(@NonNull AppComponent appComponent) {
        //如找不到该类,请编译一下项目
        DaggerCoursePlayComponent
                .builder()
                .appComponent(appComponent)
                .coursePlayModule(new CoursePlayModule(this))
                .build()
                .inject(this);
    }

    @Override
    public int initView(@Nullable Bundle savedInstanceState) {
        MobclickAgent.onEvent(getActivity(),"ttw_course_play");
        //如果你不需要框架帮你设置 setContentView(id) 需要自行设置,请返回 0
        return R.layout.courselive_activity_play;
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        vh = new ViewHolder();
        initVideoPlayer();
        btnSubmit.setChangeAlphaWhenPress(true);

        swipeLayout.setOnRefreshListener(() -> getData(true));
        rvList.setAdapter(mAdapter);
//        mAdapter.setOnLoadMoreListener(() -> getData(false), rvList);
        rvList.setLayoutManager(layoutManager);
        getData(true);
    }

    private void getData(boolean pullToRefresh) {
        mPresenter.getResourceDetail(pullToRefresh, mData.getInternalId(), mData.getParentId());
    }

    private void initVideoPlayer() {

        //外部辅助的旋转，帮助全屏
        orientationUtils = new OrientationUtils(this, vh.mVideoPlayer);
        //初始化不打开外部的旋转
        orientationUtils.setEnable(false);
        vh.mVideoPlayer.setBottomProgressBarDrawable(null);
        gsyVideoOption = new GSYVideoOptionBuilder();
        gsyVideoOption
                .setIsTouchWiget(true)
                .setRotateViewAuto(false)
                .setLockLand(false)
                .setAutoFullWithSize(true)
                .setShowFullAnimation(false)
                .setNeedLockFull(true)
                .setBottomProgressBarDrawable(null)
                .setCacheWithPlay(false)
                .setVideoAllCallBack(new GSYSampleCallBack() {
                    @Override
                    public void onPrepared(String url, Object... objects) {
                        super.onPrepared(url, objects);
                        //开始播放了才能旋转和全屏
                        orientationUtils.setEnable(true);
                        isPlay = true;
                    }

                    @Override
                    public void onEnterFullscreen(String url, Object... objects) {
                        super.onEnterFullscreen(url, objects);
                    }

                    @Override
                    public void onAutoComplete(String url, Object... objects) {
                        super.onAutoComplete(url, objects);
                    }

                    @Override
                    public void onClickStartError(String url, Object... objects) {
                        super.onClickStartError(url, objects);
                    }

                    @Override
                    public void onQuitFullscreen(String url, Object... objects) {
                        super.onQuitFullscreen(url, objects);
                        if (orientationUtils != null) {
                            orientationUtils.backToProtVideo();
                        }
                    }

                    @Override
                    public void onPlayError(String url, Object... objects) {
                        showMessage("视频播放出错");
                    }
                })
                .setLockClickListener((view, lock) -> {
                    if (orientationUtils != null) {
                        //配合下方的onConfigurationChanged
                        orientationUtils.setEnable(!lock);
                    }
                })
                .setGSYVideoProgressListener((progress, secProgress, currentPosition, duration)
                        -> Debuger.printfLog(" progress " + progress + " secProgress " + secProgress + " currentPosition " + currentPosition + " duration " + duration));

        vh.mVideoPlayer.getFullscreenButton().setOnClickListener(v -> {
            //直接横屏
            orientationUtils.resolveByClick();

            //第一个true是否需要隐藏actionbar，第二个true是否需要隐藏statusbar
            vh.mVideoPlayer.startWindowFullscreen(getActivity(), true, true);
        });

    }

    private GSYVideoPlayer getCurPlay() {
        if (vh.mVideoPlayer != null && vh.mVideoPlayer.getFullWindowPlayer() != null) {
            return vh.mVideoPlayer.getFullWindowPlayer();
        }
        return vh.mVideoPlayer;
    }

    @Override
    public void onBackPressed() {
        if (orientationUtils != null) {
            orientationUtils.backToProtVideo();
        }

        if (GSYVideoManager.backFromWindowFull(this)) {
            return;
        }
        super.onBackPressed();
    }

    @Override
    public void showLoading() {
        if (swipeLayout != null) {
            emptyView.show(true);
            swipeLayout.setEnabled(false);
        }
    }

    @Override
    public void hideLoading() {
        if (swipeLayout != null) {
            emptyView.hide();
            swipeLayout.setRefreshing(false);
            swipeLayout.setEnabled(true);
        }
    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        RxUtil.showTipDialog(getActivity(), QMUITipDialog.Builder.ICON_TYPE_NOTHING, message);
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {
        finish();
    }

    @Override
    public Activity getActivity() {
        return this;
    }

    @Override
    public void update(CoursePlayData data) {
        this.mCoursePlayData = data;
        if (mAdapter.getHeaderLayoutCount() <= 0) {
            mAdapter.addHeaderView(vh.header);
            //增加封面
            ImageView imageView = new ImageView(this);
            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            Glide.with(this)
                    .load(data.getPreImage())
                    .transition(DrawableTransitionOptions.withCrossFade())
                    .into(imageView);
            gsyVideoOption.setThumbImageView(imageView);
            gsyVideoOption
                    .setUrl(data.getUrl())
                    .setVideoTitle(data.getTitle())
                    .build(vh.mVideoPlayer);
            vh.mVideoPlayer.getStartButton().setOnClickListener(v -> {
                if (data.isIsBuy() || Integer.valueOf(data.getPrice()) == 0) {
                    if (vh.mVideoPlayer.isInPlayingState()) {
                        if (vh.mVideoPlayer.getCurrentState() == GSYVideoView.CURRENT_STATE_PAUSE) {
                            vh.mVideoPlayer.onVideoResume();
                        } else {
                            vh.mVideoPlayer.onVideoPause();
                        }
                    } else {
                        vh.mVideoPlayer.startPlayLogic();
                    }
                } else {
                    showMessage("请先购买课程");
                }
            });
        }
        if (data.getColor() == 1) {
            vh.mTvStatus.setSelected(true);
        }
        vh.mRatingBar.setRating((float) data.getStar());
//        vh.mTvCommentNo.setText(data.getCommetData().getCount() + "人");
        vh.mTvStatus.setText(data.getPlayInfo());
        vh.mTvTitle.setText(data.getTitle());
        vh.mTvPrice.setText(ObjectUtils.isEmpty(data.getPrice()) ? "¥0" : "¥" + data.getPrice());
        vh.mTvContent.setText(RxUtil.fromHtml(data.getDescription()));
        if (data.isIsBuy()) {
            vh.mBtnBuy.setVisibility(View.INVISIBLE);
            btnSubmit.setVisibility(View.GONE);
            btnSubmit.setText("我要评价");
        } else {
            vh.mBtnBuy.setVisibility(View.VISIBLE);
        }
            btnSubmit.setVisibility(View.GONE);
    }

    @Override
    public void loadFail() {
        if (ObjectUtils.isNotEmpty(emptyView)) {
            emptyView.show(
                    false,
                    getResources().getString(R.string.public_emptyView_mode_desc_fail_title),
                    null,
                    getResources().getString(R.string.public_emptyView_mode_desc_retry),
                    v -> {
                        getData(true);
                    });

        }
    }

    @OnClick({R2.id.btn_submit})
    public void onClick(View v) {
        int i = v.getId();
        if (i == R.id.btn_submit) {
            if (mCoursePlayData.isIsBuy()) {
                Utils.customNavigation(RouterHub.COURSELIVE_COURSELIVECOMMENTACTIVITY, Constants.COMMENT, mData);
            }
        }
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        //如果旋转了就全屏
        if (isPlay && !isPause) {
            vh.mVideoPlayer.onConfigurationChanged(this, newConfig, orientationUtils, true, true);
        }
    }

    @Subscriber(tag = RouterHub.COURSELIVE_COURSEPLAYACTIVITY)
    public void onEvents(Message msg) {
        switch (msg.what) {
            case EventBusTags.PAY_SUCCESS:
                getData(true);
                break;
            case EventBusTags.COMMENT_SUCCESS:
                getData(true);
                break;
            default:
        }
    }

    class ViewHolder {
        View header;
        @BindView(R2.id.videoPlayer)
        LandLayoutVideo mVideoPlayer;
        @BindView(R2.id.tv_title)
        TextView mTvTitle;
        @BindView(R2.id.tv_status)
        TextView mTvStatus;
        @BindView(R2.id.tv_price)
        TextView mTvPrice;
        @BindView(R2.id.btn_buy)
        QMUIRoundButton mBtnBuy;
        @BindView(R2.id.tv_content)
        TextView mTvContent;
        @BindView(R2.id.tv_comment_no)
        TextView mTvCommentNo;
        @BindView(R2.id.ratingBar)
        RatingBar mRatingBar;

        ViewHolder() {
            header = View.inflate(getActivity(), R.layout.courselive_activity_play_header, null);
            ButterKnife.bind(this, header);
            mBtnBuy.setChangeAlphaWhenPress(true);
        }

        @OnClick({R2.id.btn_buy})
        public void onClick(View v) {
            int i = v.getId();
            if (i == R.id.btn_buy) {
                MobclickAgent.onEvent(getActivity(),"ttw_course_buy");
                ARouter.getInstance().build(RouterHub.COURSELIVE_ORDERPAYACTIVITY)
                        .withString(Intent.EXTRA_TITLE, Constants.ORDERPAY)
                        .withInt(Constants.ROUTER_INTEGER, mData.getInternalId())
                        .navigation(getActivity());

            }
        }
    }
}